<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form ref="loginForm" @submit="Login">
      <van-field
        name="mobile"
        placeholder="请输入手机号码"
        center
        v-model="user.mobile"
        :rules="formRules.mobile"
      >
        <i class="totiao totiao-shouji" slot="left-icon"></i>
      </van-field>

      <van-field
        placeholder="请输入验证码"
        center
        v-model="user.code"
        :rules="formRules.code"
      >
        <i class="totiao totiao-yanzhengma" slot="left-icon"></i>
        <template #button>
          <van-count-down
            :time="time"
            v-if="sending"
            format="ss 秒"
            @finish="sending = false"
          />
          <van-button
            round
            size="small"
            type="default"
            @click="sendCode"
            native-type="button"
            v-else
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button
          block
          type="info"
          native-type="submit"
          :loading="loading"
          loading-type="spinner"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { sendSmsAPI, LoginAPI } from "@/api";
export default {
  data() {
    return {
      user: {
        mobile: "",
        code: "",
      },
      formRules: {
        mobile: [
          { required: true, message: "手机号码不能为空" },
          { pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: "手机号码不正确" },
        ],
        code: [{ pattern: /^\d{4,6}$/, message: "验证码不正确" }],
      },
      time: 60000,
      sending: false,
      loading: false,
    };
  },
  methods: {
    async sendCode() {
      await this.$refs.loginForm.validate("mobile"); // 调用表单validate方法 注意是表单的方法，所以要先获取表单元素，返回的是一个Promise 验证表单，支持传入 name 来验证单个或部分表单项

      // console.log("验证码校验手机号表单成功");
      await sendSmsAPI(this.user.mobile);
      this.$toast.success("发送验证码成功");
      this.sending = true;
    },
    async Login() {
      this.loading = true;
      // console.log("表单提交了");
      try {
        const res = await LoginAPI(this.user);
        // localStorage.setItem("token", res.data.token);
        this.$store.commit("setUser", res.data);
        this.$toast.success("登陆成功");
        this.$router.push("/my");
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
</style>